import URLImage from '@/components/URLImage'
import Konva from 'konva'
import { useEffect, useRef, useState } from 'react'
import { Group, Layer, Line, Stage, Text } from 'react-konva'

export default function View() {
  const [tool, setTool] = useState('pen')
  const [lines, setLines] = useState([])
  const isDrawing = useRef(false)
  const groupRef = useRef<Konva.Group>(null)

  const handleMouseDown = e => {
    isDrawing.current = true
    const pos = e.target.getStage().getPointerPosition()
    setLines([...lines, { tool, points: [pos.x, pos.y] }])
  }

  const handleMouseMove = e => {
    if (!isDrawing.current) {
      return
    }
    const stage = e.target.getStage()
    const point = stage.getPointerPosition()
    const lastLine = lines[lines.length - 1]
    lastLine.points = lastLine.points.concat([point.x, point.y])
    lines.splice(lines.length - 1, 1, lastLine)
    setLines(lines.concat())
  }

  const handleMouseUp = () => {
    isDrawing.current = false
  }

  useEffect(() => {
    groupRef.current.cache()
  }, [lines])

  return (
    <div>
      <select
        value={tool}
        onChange={e => {
          setTool(e.target.value)
        }}
      >
        <option value='pen'>Pen</option>
        <option value='eraser'>Eraser</option>
      </select>
      <Stage
        width={window.innerWidth}
        height={window.innerHeight}
        onMouseDown={handleMouseDown}
        onMousemove={handleMouseMove}
        onMouseup={handleMouseUp}
      >
        <Layer>
          <Text text='Just start drawing' x={5} y={30} />
          <URLImage src='https://konvajs.org/assets/yoda.jpg' x={150} y={150} />
          <Group ref={groupRef}>
            <URLImage src='https://konvajs.org/assets/yoda.jpg' x={350} y={350} />
            {lines.map((line, i) => (
              <Line
                key={i}
                points={line.points}
                stroke='#df4b26'
                strokeWidth={5}
                tension={0.5}
                lineCap='round'
                lineJoin='round'
                globalCompositeOperation={line.tool === 'eraser' ? 'destination-out' : 'source-over'}
              />
            ))}
          </Group>
        </Layer>
      </Stage>
    </div>
  )
}
